package com.zcs.app.lucky.ui

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import cn.sxw.android.base.adapter.CommonRecyclerAdapter
import cn.sxw.android.base.bean.GlideEngine
import cn.sxw.android.base.dialog.CustomDialogHelper
import cn.sxw.android.base.kt.BaseViewModel
import cn.sxw.android.base.utils.GlideStaticUtils
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.safframework.delegate.extras.extraDelegate
import com.zcs.app.lucky.R
import com.zcs.app.lucky.base.BaseLuckyActivity
import com.zcs.app.lucky.data.PrizeDataCache
import com.zcs.app.lucky.databinding.ActivityAddPrizeBinding
import com.zcs.app.lucky.entity.LevelEntity
import com.zcs.app.lucky.entity.levelList
import com.zcs.app.lucky.ui.clip.AvatarClipActivity

class AddPrizeActivity : BaseLuckyActivity<ActivityAddPrizeBinding, BaseViewModel>() {
    companion object {
        const val KEY_PRIZE_ID = "KEY_PRIZE_ID"
    }

    private val mPrizeId: String by extraDelegate(KEY_PRIZE_ID, "")
    private val mPrize by lazy {
        PrizeDataCache.findById(mPrizeId)
    }

    override fun onReady() {
        binding.toolbar.tvToolbarTitle.text = if (isModify()) "编辑奖品" else "添加奖品"
        binding.loadingLayout.visibility = View.VISIBLE
        if (isModify()) {
            binding.toolbar.tvToolbarRight.text = "删除"
        }
    }

    override fun onInit() {
        initView()
    }

    override fun initObserve() {
    }

    override fun initData() {
        // hide loading last
        hideLoading()

        mItems.clear()
        mItems.addAll(levelList())

        if (isModify()) {
            showPic()
            binding.etName.setText(mPrize.name)
            binding.etMaxCount.setText(mPrize.maxCount.toString())
            for ((i, level) in mItems.withIndex()) {
                if (mPrize.level!!.id == level.id) {
                    level.isChecked = true
                    lastPosition = i
                    break
                }
            }
        }

        initLevelAdapter()
    }

    private var mAdapter: CommonRecyclerAdapter<LevelEntity>? = null
    private var mItems = ArrayList<LevelEntity>()
    var lastPosition = -1

    private fun initLevelAdapter() {
        if (mAdapter == null) {
            mAdapter =
                object : CommonRecyclerAdapter<LevelEntity>(R.layout.item_prize_level, mItems) {
                    override fun convert(holder: BaseViewHolder, item: LevelEntity) {
                        holder.setText(R.id.tvName, item.name)
                        val tvName = holder.getView<TextView>(R.id.tvName)
                        tvName.isSelected = item.isChecked
                        tvName.setOnClickListener {
                            val currPosition = holder.absoluteAdapterPosition
                            if (lastPosition == currPosition) {
                                return@setOnClickListener
                            }
                            if (lastPosition != -1) {
                                mItems[lastPosition].isChecked = false
                                notifyItemChanged(lastPosition)
                            }
                            item.isChecked = !item.isChecked
                            notifyItemChanged(currPosition)
                            lastPosition = currPosition
                            mPrize.level = item
                        }
                    }
                }
            binding.rvLevel.adapter = mAdapter
            if (lastPosition != -1) {
                binding.rvLevel.scrollToPosition(lastPosition)
            }
        } else {
            mAdapter!!.notifyDataSetChanged()
        }
    }

    private fun showPic() {
        GlideStaticUtils.displayRoundedImage(
            mPrize.pic,
            R.mipmap.ic_add_pic,
            binding.ivThumb,
            false,
            20
        )
    }

    override fun initView() {
        initData()
    }

    override fun hideLoading() {
        super.hideLoading()
        binding.loadingLayout.visibility = View.GONE
    }

    override fun addOnClickListener() {
        binding.toolbar.ivToolbarBack.setOnClickListener { onBackPressed() }
        if (isModify()) {
            binding.toolbar.tvToolbarRight.setOnClickListener {
                CustomDialogHelper.showCustomConfirmDialog(
                    this@AddPrizeActivity,
                    "你确定要删除该奖品吗?",
                    object : CustomDialogHelper.NativeDialogCallback {
                        override fun onConfirm() {
                            PrizeDataCache.removeById(mPrizeId, true)
                            killMyself()
                        }

                        override fun onCancel() {}
                    })
            }
        }
        binding.ivThumb.setOnClickListener {
            onOpenAlbum()
        }
        binding.btnSave.setOnClickListener {
            onSave()
        }
    }

    @SuppressLint("CheckResult")
    fun onOpenAlbum() {
        rxPermissions.request(
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
        ).subscribe {
            if (it) {
                openAlbum()
            } else {
                // 授权失败
                onNeverAsk("文件存储/相机", withExit = true, true)
            }
        }
    }

    private fun openAlbum() {
        val fileProviderName = "$packageName.FileProvider"
        EasyPhotos.createAlbum(this, true, false, GlideEngine.getInstance())
            .setPuzzleMenu(false) //不显示拼图按钮
            .setCleanMenu(false) //不显示清除按钮
            .setFileProviderAuthority(fileProviderName) //参数说明：见下方`FileProvider的配置`
            .setCount(1)
            .start(codePic)
    }
    private val codePic = 0x001// 选图
    private var mPicture: Photo? = null
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK) {
            when (requestCode) {
                codePic -> {// 处理图片
                    if (data == null) return
                    //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
                    val resultPhotos: ArrayList<Photo> =
                        data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS)
                    mPicture = resultPhotos.firstOrNull()
                    if (mPicture != null) {
                        val path = mPicture?.path ?: ""
                        if (path.isNotEmpty()) {
                            openClip(path)
                        }
                    }
                }
            }
        }
    }

    private fun openClip(path: String) {
        val intent = Intent(this, AvatarClipActivity::class.java)
        intent.putExtra("PATH", path)
        intent.putExtra("IS_CIRCLE", false)
        clipResultLauncher.launch(intent)
    }

    private fun onSave() {
        if (mPrize.pic.isEmpty()) {
            showToast("请为照片选择一张预览图")
            return
        }
        val name = binding.etName.text.toString().trim()
        if (name.isEmpty()) {
            showToast("请输入奖品名称")
            return
        }
        if (mPrize.level == null) {
            showToast("请选择奖品等级")
            return
        }
        val maxCount = binding.etMaxCount.text.toString().trim()
        if (maxCount.isEmpty()) {
            showToast("请输入奖品最大名额")
            return
        }

        mPrize.name = name
        mPrize.maxCount = maxCount.toInt()
        PrizeDataCache.addPrize(mPrize, isModify())
        showToast("保存成功")
        killMyself()
    }

    private fun isModify(): Boolean = !TextUtils.isEmpty(mPrizeId)


    private lateinit var clipResultLauncher: ActivityResultLauncher<Intent>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // registerForActivityResult  注:必须在onCreate内注册，有点劝退的感觉
        clipResultLauncher =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == Activity.RESULT_OK) {
                    mPrize.pic = it.data?.getSerializableExtra("CLIP_AVATAR") as String
                    if (mPrize.pic.isNotEmpty()) {
                        showPic()
                    } else {
                        showMessage("照片选取失败，请重试")
                    }
                }
            }
    }
}